import re

class PlsParser:
    patterns = { 'file' : re.compile(r'file\d+\s*=\s*(.*)$', re.I),
                 'title' : re.compile(r'title\d+\s*=\s*(.*)$', re.I),
                 'length' : re.compile(r'length\d+\s*=\s*(-?\d+)$', re.I)}

    def __init__(self):
        pass

    def parse_file(self, file):
        streams = []
        stream = {}
        for line in file:
            line = line.strip()
            # Match all patterns against the line.
            matches = {}
            for key, pattern in PlsParser.patterns.items():
                matches[key] = pattern.match(line)
            # Find the (single) match and store it. If we see any key that we
            # have already stored, assume that entry is complete and add it to
            # "streams". This avoids assumptions regarding order.
            for key, match in matches.items():
                if match:
                    # If we saw this key already, assume the entry is complete.
                    if stream.has_key(key):
                        streams.append(stream)
                        stream = {}
                    stream[key] = match.group(1)
                    break
        # Flush last entry.
        if stream: streams.append(stream)
        return streams
